package com.yunshang.shoppingmall.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.xpath.internal.operations.Or;
import com.yunshang.shoppingmall.common.*;
import com.yunshang.shoppingmall.entity.*;
import com.yunshang.shoppingmall.mapper.OrderExportMapper;
import com.yunshang.shoppingmall.service.*;
import com.yunshang.shoppingmall.service.User.UserRankService;
import org.apache.catalina.Session;
import org.apache.http.entity.ContentType;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Controller
public class ExportController {
    @Autowired
    UserRankService userRankService;
    @Autowired
    CartService cartService;
    @Autowired
    ExportOrderService exportOrderService;
    @Autowired
    OrderExportService orderExportService;
    @Autowired
    DemolitionOrderService demolitionOrderService;
    @Autowired
    AddressService addressService;
    @Autowired
    ConfigService configService;
    @Autowired
    OrderService orderService;

    @Autowired
    ExportService exportService;
    @ResponseBody
    @RequestMapping("/Excel")
    @Transactional
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        exportService.exportExcel(request,response);
    }

    @ResponseBody
    @Transactional
    @RequestMapping("/exportExcelqw")
    public void exportExcelqw(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //exportService.exportExcel(request,response);
    }

    public void exportExcelOLD(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<RemoveUserAndAddress> listOther=new ArrayList<>();//存放去重的用户收货信息
        List<OrderExport> listEx1 = orderExportService.getOrderExportData1();//
        List<OrderExport> listEx2 = orderExportService.getOrderExportData2();//
        listEx1.addAll(listEx2);
        List<OrderExport> list = listEx1;//导单数据
        List<OrderExport> listTemp=new ArrayList<>();//特殊产品
        List<OrderExport> listTempOther=new ArrayList<>();//特殊以外的其他产品数据
        List<OrderExport> listTempSupplier=new ArrayList<>();//供货商产品数据
        List<DemolitionOrder> demolitionOrders=demolitionOrderService.selectAll();//需要进行拆单的基础数据
        HashSet<String> hashSet=new HashSet<>();//订单编号
        int number=0;//导单数量
        int up=0;
        //excel标题
        String[] title = {"业务单号","收件人姓名","收件人手机","收件人地址","品名","数量","备注","订单号"};
//        String[] title = {"业务单号","收件人姓名","收件人手机","收件人地址","品名","数量","备注"};
        //excel文件名
        String fileName = "物流导单"+System.currentTimeMillis()+".xls";
        //业务单号
        DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        String busidstr = format2.format(new Date());
        //sheet名
        String error="";
        String sheetName = "HSYS"+busidstr;
        OrderExport errorOO=new OrderExport();
        Set<String> listSupplier=new HashSet<>();
        String supName="";
        String suname="贵州荟生生物科技有限公司";
        try {
            for (int i = 0; i < list.size(); i++) {
                OrderExport orderExport = list.get(i);
                String supplier = orderExport.getSupplier() == null ? "" : orderExport.getSupplier();
                if ("".equals(supplier)) {
                    supName = "未知";
                } else {
                    supName = supplier;
                }
                if(!supName.equals(suname)){
                    listSupplier.add(supName);
                }

                //System.out.println("orderExport:"+orderExport.toString());
                //System.out.println("supNameXXX:"+supName);
                //System.out.println("orderExport.getSupplier():"+orderExport.getSupplier());
                errorOO = list.get(i);
                //System.out.println("订单编号:"+orderExport.getOrderNo());
                String[] strings = orderExport.getOrderNo().split(",");
                if (strings.length == 1) {
                    hashSet.add(orderExport.getOrderNo());
                } else {
                    for (String str : strings) {
                        hashSet.add(str);
                    }
                }
                //获取所有用户收货信息
                RemoveUserAndAddress orderExport1 = new RemoveUserAndAddress();
//                int type=orderExport.getType();
//                if(type==1){
//                    orderExport.setLogname(orderExport.getLogname1());
//                    orderExport.setPhone(orderExport.getPhone1());
//                    orderExport.setGuigeName(orderExport.getProductName());
//                    orderExport.setGuigeName1(orderExport.getProductName1());
//                    orderExport.setAddressAll(orderExport.getAddressAll1());
//                    orderExport.setProductCount(orderExport.getpCount());
//                }
                //2为正常下单 1换产品
//                orderExport1.setUserId(orderExport.getUserId());
                orderExport1.setLogname(orderExport.getLogname());
                orderExport1.setPhone(orderExport.getPhone());
                orderExport1.setAddressAll(orderExport.getAddressAll());
                String name = list.get(i).getGuigeName1();
                //orderExport1.setAddressId(orderExport.getAddressId());
                listOther.add(orderExport1);
                //获取所有用户收货信息结束
                int productId = 0, guigeId = 0, productCount = 0;
                productId = list.get(i).getProductId();
                guigeId = list.get(i).getGuigeId();
                productCount = list.get(i).getProductCount();
                //判断产品大于一定数量是否拆单 &&productCount>str.getNumber()  &&productCount>str.getNumber()
                int finalProductId = productId;
                int finalGuigeId = guigeId;
                //判断产品大于一定数量是否拆单 &&productCount>str.getNumber()  &&productCount>str.getNumber()
                boolean isChai = demolitionOrders.stream().anyMatch(str -> (finalProductId == str.getProductid() && finalGuigeId == str.getGuigeid() && str.getType() == 1));
                boolean isChai1 = demolitionOrders.stream().anyMatch(str -> (finalProductId == str.getProductid() && finalGuigeId == str.getGuigeid() && str.getType() == 2));
                if (!suname.equals(supName)) {
                    listTempSupplier.add(orderExport);
                } else if (isChai) {//类型为1拆单
                    for (int n = 0; n < productCount; n++) {
                        OrderExport orderExportTemp = orderExport;
                        orderExportTemp.setGuigeName(name + "*" + 1);
                        listTemp.add(orderExportTemp);
                        System.out.println("a5");
                        number++;
                    }
                } else if (isChai1) {//类型为2拆单
                    int c = productCount / 6;// a-(a/b)*b
                    if (c == 1) {//单瓶整除为1
                        OrderExport orderExportTemp = exportService.orderGroup(orderExport);
                        orderExportTemp.setGuigeName(name + "*" + 6);
                        listTemp.add(orderExportTemp);
                        System.out.println("a4");
                        number++;
                    }
                    if (c > 1) {//单瓶整除大于1
                        for (int n = 0; n < c; n++) {
                            OrderExport orderExportTemp = exportService.orderGroup(orderExport);
                            orderExportTemp.setGuigeName(name + "*" + 6);
                            listTemp.add(orderExportTemp);
                            System.out.println("a3");
                            number++;
                        }
                    }
                    if (productCount % 6 != 0) {//处理剩下不到一件的
                        int d = productCount - (productCount / 6) * 6;
                        OrderExport orderExportTemp = exportService.orderGroup(orderExport);
                        orderExportTemp.setGuigeName(name + "*" + d);
                        System.out.println("a2");
                        listTemp.add(orderExportTemp);
                        number++;
                    }
                } else {
                    //添加到特殊产品拆单以外的其它集合
                    listTempOther.add(orderExport);
                }
            }
            List<String> listSup = new ArrayList<>(listSupplier);
            //根据用户合并其它产品
            //去除用户重复的收货信息
            List<RemoveUserAndAddress> list1 = exportService.removeDuplicate(listOther);

            //根据去重的用户收货信息进行整合特殊以外产品信息
            //  list1.forEach(item ->{
            List<OrderExport> listTempXX = new ArrayList<>();
            for (String str : listSupplier) {
                //System.out.println("listSupplier:"+str);
                for (RemoveUserAndAddress item : list1) {
                    List<OrderExport> list2 = listTempSupplier.stream().filter(c -> (
                            c.getLogname() != null && c.getLogname().equals(item.getLogname()) &&
                                    c.getPhone() != null && c.getPhone().equals(item.getPhone()) &&
                                    c.getAddressAll() != null && c.getAddressAll().equals(item.getAddressAll()))
                    ).collect(Collectors.toList());
                    Collections.sort(list2, Comparator.comparingInt(OrderExport::getProductCount));//根据数量排序
                    if (list2 != null && list2.size() > 0) {
                        listTempXX = exportService.assOrderDataName(list2,str);
                    }
                    if (list2 != null && list2.size() > 0) {
                        if(listTempXX!=null&&listTempXX.size()>0){
                            List<OrderExport> list1q=listTempXX.stream().filter(c -> (!c.getOrderNo().equals("null")&&!c.getOrderNo().equals("")))
                                    .collect(Collectors.toList());
                            listTempXX=list1q;
                            listTemp.addAll(listTempXX);
                            number = number + listTempXX.size();
                        }
                    }
                }
            }
            //System.out.println("listTemp1:"+listTempXX);
            //System.out.println("listTempOther:"+listTempOther.size());
            for (RemoveUserAndAddress item : list1) {
                List<OrderExport> list2 = listTempOther.stream().filter(c -> (
//                                    c.getUserId()!=null&&c.getUserId().equals(item.getUserId())&&
                                c.getLogname() != null && c.getLogname().equals(item.getLogname()) &&
                                        c.getPhone() != null && c.getPhone().equals(item.getPhone()) &&
                                        c.getAddressAll() != null && c.getAddressAll().equals(item.getAddressAll()))
                ).collect(Collectors.toList());
                Collections.sort(list2, Comparator.comparingInt(OrderExport::getProductCount));//根据数量排序
                List<OrderExport> listTemp1 = new ArrayList<>();
                if (list2 != null && list2.size() > 0) {
                    listTemp1 = exportService.assOrderData(list2);
                }

                //再次进行组合
//                List<OrderExport> orderExportTwo=new ArrayList<>();
//                List<OrderExport> orderExportTwo1=new ArrayList<>();
//                for (OrderExport orderExport:listTemp1) {
//                    if(orderExport.getGuigeName().split("\\+").length==1){
//                        orderExportTwo.add(orderExport);
//                    }else {
//                        orderExportTwo1.add(orderExport);
//                    }
//                    System.out.println(orderExport.getGuigeName()+"--"+orderExport.getGuigeName1()+"--"+orderExport.getProductCount()+"--"+orderExport.getProWeight());
//                }
//                List<OrderExport> listTemp2=assOrderData(orderExportTwo,"1");
//                listTemp.addAll(orderExportTwo1);
//                listTemp.addAll(listTemp2);
                //System.out.println("a1");
                if (list2 != null && list2.size() > 0) {
                    if(listTemp1!=null&&listTemp1.size()>0){
                        listTemp.addAll(listTemp1);
                        number = number + listTemp1.size();
                    }
                }
                //System.out.println("listTemp2:"+listTemp1);
            }

        }catch(Exception e){
            up = 1;
            error = e.toString() + "订单数据有误：" + errorOO.getOrderNo();
        }
        //组合数据添加到Excel
        if(listTemp!=null&&listTemp.size()>0){
            Collections.sort(listTemp, Comparator.comparing(OrderExport::getLogname));//排序
        }

        String [][] content=new String[listTemp.size()][];
//
//        if(listTemp.size()<=0){
//            content=new String[1][];
//            content[0] = new String[title.length];
//            if(error.equals("")){
//                content[0][0] = "空空如也!";content[0][1] = "空空如也!";content[0][2] = "空空如也!";content[0][3] = "空空如也!";
//                content[0][4] = "空空如也!";content[0][5] = "空空如也!";content[0][6] = "空空如也!";
//            }else {
//                content[0][0] = error;
//            }
//        }
//        for (int i = 0; i < listTemp.size(); i++){
//            OrderExport orderExport=listTemp.get(i);
//            content[i] = new String[title.length];
//            content[i][0] = busidstr+"-"+(i+1);//业务单号
//            content[i][1] = orderExport.getLogname();
//            content[i][2] = orderExport.getPhone();
//            content[i][3] = orderExport.getAddressAll();
//            content[i][4] = orderExport.getGuigeName();
//            content[i][5] = "";
//            content[i][6] = orderExport.getSupplier();
//            content[i][7] =orderExport.getOrderNo();
//        }
        //创建HSSFWorkbook
        listSupplier.add(suname);
        List<String> listSup1 = new ArrayList<>(listSupplier);
        listSup1.remove(suname);
        List<String> ss=new ArrayList<>();
        ss.add(suname);
        ss.addAll(listSup1);
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null,ss,listTemp);

        //
        String url="";
        //保存excel
        try {
            String path="/usr/local/mall_uploads/logistics";
            File uploadPath=new File(path);
            if(!uploadPath.exists()){
                uploadPath.mkdirs();
            }
            System.out.println("surl:"+uploadPath+"/"+fileName);
            FileOutputStream fileOut = new FileOutputStream(uploadPath+"/"+fileName);
            url="/logistics/"+fileName;
            wb.write(fileOut);
            fileOut.close();
        }
        catch (Exception e){
            e.printStackTrace();
            up=1;
        }
        //响应到客户端
        try {
            exportService.setResponseHeader(response,fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            up=1;
        }
        if(up==0){
            //更新为导单状态
            List lists=null;
            try {
                Object[] list1X=hashSet.toArray();
                String[] stringArray = Arrays.copyOf(list1X, list1X.length, String[].class);
                lists = java.util.Arrays.asList(stringArray);
            }catch (Exception e){
                //System.out.println(e.getMessage());
            }
            if(lists!=null&&lists.size()>0){
                HttpSession session=request.getSession();
                Integer adminid= (Integer) session.getAttribute("adminId");
                String orderNos=hashSet.toString().trim().replace('[','(').replace(']',')');
                int res=orderService.upOrderFrom(lists,new Date());
                ExportOrder exportOrder=new ExportOrder();
                exportOrder.setNumber(number);
                exportOrder.setType(1);
                exportOrder.setTypename("快递");
                exportOrder.setUrl(url);
                exportOrder.setTime(new Date());
                exportOrder.setOrdernos(orderNos);
                exportOrder.setAdminuserid(adminid);
                int res1=exportOrderService.insertSelective(exportOrder);
                System.out.println("状态更新成功！！！");

            }
        }
    }

    //读取excel
    @RequestMapping("/importExcel")
    public String importExcel(){
        return "export/export";
    }


    //读取Excel
    @RequestMapping("/readExcel")
    @ResponseBody
    @Transactional
    public String readExcel(MultipartFile file,HttpServletRequest request,HttpServletResponse response){
        try {
            List<String[]> list=ExcelUtil.readExcel(file);
            int count=0;
            for (int i = 0; i < list.size(); i++) {
                String orderNumber="";
                String logisicalNo="";
                int a3=0;
                //@Param("cartsList")
                List<String> orderList=new ArrayList<>();
                String[] strings = list.get(i);
//                for (int j = 0; j <strings.length; j++) {
                String a1=list.get(0)[0];
                String a2=list.get(0)[1];
                try {
                    a3=list.get(0)[2]==null?0:Integer.parseInt(list.get(0)[2]);
                }catch (Exception e){}
                if("订单号".equals(a1)&&"物流单号".equals(a2)){
                    String s1=strings[0]==null?"":strings[0];
                    String s2=strings[1]==null?"":strings[1];
                    if(!"".equals(s1)&&!"".equals(s2)){
                        if(i!=0){
                            String ss=strings[0].trim().
                                    replace("，",",").
                                    replace(",,",",").
                                    replace(" ",",").
                                    replace("  ",",");
                            String []orderStr=ss.split(",");
                            for (String str: orderStr ) {
                                orderNumber=str.trim();
                                orderList.add(orderNumber);
                            }
                            logisicalNo=strings[1].trim();
                        }
                    }else if("".equals(s1)&&"".equals(s2)) {
                        continue;
                    }else {
                        String s="";
                        if(orderList!=null&&orderList.size()>0){
                            s=orderList.get(0);
                        }
                        return "失败:第"+(i+1)+"行数据有误！"+s+"--"+logisicalNo;
                    }
                }else {
                    return "失败:标题1为订单号，标题2为物流单号！";
                }
                //hashMap.put(orderNumber,logisicalNo);
                //                    else if("姓名".equals(list.get(0)[j].toString()))
//                    {
//                        System.out.println("姓名:"+strings[j].toString());
//                    }
//                    else if("电话".equals(list.get(0)[j].toString()))
//                    {
//                        System.out.println("电话:"+strings[j].toString());
//                    }
//                    else if("地址".equals(list.get(0)[j].toString()))
//                    {
//                        System.out.println("地址:"+strings[j].toString());
//                    }
//                    else if("数量".equals(list.get(0)[j].toString()))
//                    {
//                        System.out.println("数量:"+strings[j].toString());
//                    }
//                    else if("商品".equals(list.get(0)[j].toString()))
//                    {
//                        System.out.println("商品:"+strings[j].toString());
//                    }
//                    else
//                    {
//                        //System.out.println(strings[j].toString());
//                    }
//                }
                if((logisicalNo != null && logisicalNo.length()!= 0)&&(orderNumber != null && orderNumber.length()!= 0)) {
                    int res=0;
//                    if(a3>0){
//                        res = cartService.updateLogByOrderNoAndNumber(logisicalNo, orderList,a3+"");
//                    }else {
//                        res = cartService.updateLogByOrderNo(logisicalNo, orderList);
//                    }
//                    11001  D12
//                    11002  D12
                    for (String str:orderList) {
                        if(str!=null&&!str.equals("")) {
                            List<Cart> cartList = cartService.selectByOrderNo(str);
                            if(cartList!=null&&cartList.size()>0){
                                Set<String> setorno = new HashSet();
                                for (Cart cart:cartList) {
                                    String logNo=cart.getLogisticalNo()==null?"":cart.getLogisticalNo();
                                    if(!"".equals(logNo)){
                                        for (String ss:logNo.split(",")) {
                                            if(ss!=null&&!ss.equals(""))setorno.add(ss);
                                        }
                                    }
                                }
                                setorno.add(logisicalNo);
                                String logNos="";
                                if(setorno!=null&&setorno.size()>0){
                                    List<String> list1 = new ArrayList<>(setorno);
                                    for (int f = 0; f <list1.size() ; f++) {
                                        String s=null;
                                        if(f==(list1.size()-1)){
                                            logNos +=list1.get(f);
                                        }else {
                                            logNos +=list1.get(f)+",";
                                        }
                                    }
                                }
                                List<String> list2Order=new ArrayList<>();
                                list2Order.add(str);
                                res = cartService.updateLogByOrderNo(logNos, list2Order);
                            }
                        }
                    }
//                    res = cartService.updateLogByOrderNo(logisicalNo, orderList);
                    int res1=orderService.updateOrderStatus1("703",orderList);
                    if (res <= 0&&res1<=0) {
                        return "更新失败:"+orderNumber;
                    }else {
                        count =count+1;
                    }
                }
            }
            return "总数量："+(list.size()-1)+" 成功数量："+count;
        }
        catch (Exception e){
            e.printStackTrace();
            System.out.println("-----s"+e.getMessage());
            return e.getMessage();
        }
    }

    //导单页面
    @RequestMapping("/exportOrder")
    public String exportOrder(){
        System.out.println("-------导单页面--------->");
        return "export/exportOrder";
    }


    //导单列表首次打开查询
    @RequestMapping("/getExportOrderList")
    @ResponseBody
    public String getExportOrderList(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit){
        PageHelper.startPage(page,limit);
        List<ExportOrder> exportOrders=exportOrderService.selectListAll();
        //System.out.println(exportOrders.size()+"----------"+exportOrders.get(0).getNumber());
        PageInfo page1 = new PageInfo(exportOrders);
        return layuiJson.layuiJsonList(exportOrders,(int)page1.getTotal());
    }

    @RequestMapping("/doExport")
    @ResponseBody
    public void doExport(String path,HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        File filex = new File(ResourceUtils.getURL("/usr/local/mall_uploads/").getPath());
        //File logPath = new File(filex.getAbsolutePath(), "/logistics");
        String aFilePath=filex+path;
        File xf=new File(aFilePath);
        String aFileName = xf.getName();

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File file = null;
        file = new File(aFilePath);
        try{
            request.setCharacterEncoding("UTF-8");
            String agent = request.getHeader("User-Agent").toUpperCase();
            if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1)))
                aFileName = URLEncoder.encode(aFileName, "UTF-8");
            else {
                aFileName = new String(aFileName.getBytes("UTF-8"), "ISO8859-1");
            }
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition", "attachment; filename=" + aFileName);
            response.setHeader("Content-Length", String.valueOf(file.length()));
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
                bos.write(buff, 0, bytesRead);
            System.out.println("success");
            bos.flush();
        }catch (Exception e) {
            // TODO: handle exception
            System.out.println("导出文件失败！");
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
//                file.delete();
            } catch (Exception e) {
//               LOGGER.error("导出文件关闭流出错！", e);
            }
        }
    }

}
